const wxdb = wx.cloud.database().collection('LinuxAppDashPort')
import WxValidate from '../../utils/WxValidate'

Page({
  data: {
    portName: '',
    url: '',
    detectionHeartbeat: 1,
    array: [1, 3, 5, 10],
  },  
  bindPickerChange: function (e) {
    var that = this;
    that.setData({
      detectionHeartbeat: that.data.array[parseInt(e.detail.value)]
    })
  },
  // 弹出框
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //表单提交传入信息验证
  submitForm(e) {    
    this.setData({
      portName: e.detail.value.portName,
      url: e.detail.value.url,
      detectionHeartbeat: e.detail.value.detectionHeartbeat
    })
    const params = {
      portName: e.detail.value.portName,
      url: e.detail.value.url,
    }
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
    } else {
      var that = this
      var value = wx.getStorageSync('userinfo');
      wxdb
        .add({
          data: {
            portName: that.data.portName,
            url: that.data.url,
            detectionHeartbeat: that.data.detectionHeartbeat,
            userinfo:value
          }
        }).then(res => {
          wx.showToast({
            title: '新增成功！',
            icon: 'none',
            duration: 1500,
            complete() {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateTo({
                  url: '../index/index',
                })
              }, 1000)
            }
          })
        }).catch(res => {})
    }
  },
  // 验证字段的规则
  initValidate() {
    const rules = {
      portName: {
        required: true,
      },
      url: {
        required: true,
        url: true
      }
    }
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {      
      portName: {
        required: '请输入接口名称',
      },
      url: {
        required: '请输入接口地址',
        url: '请输入正确的接口地址'
      },
    }
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  onLoad: function (options) {
    //初始化表单
    this.initValidate();
  },
})